package com.whccb.apps.office.document.event.receive.system;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.servicetask.ServiceDelegate;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.bpms.util.ConsolePrinter;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.ODAppUtil;

public class SendRequestToGrcEvent extends ServiceDelegate {
	
	private static final Logger logger = LoggerFactory.getLogger(SendRequestToGrcEvent.class);
	
	public String getDescription() {
		return "规章制度回传GRC系统";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	public boolean execute(ProcessExecutionContext pec) throws Exception {
		BO bo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_INSTITUTION", pec.getProcessInstance().getId());
		if (bo != null) {
			// String reg_level_dict = bo.getString("REG_LEVEL_DICT");
			FormFile formFile = null;

			// 为了防止错误，所有文件一律从金格正文构建
			List<FormFile> formFiles = SDK.getBOAPI().getFiles(bo.getId(), "ZW");
			if (CollectionUtils.isNotEmpty(formFiles)) {
				formFile = formFiles.get(0);
			}

			DCContext dc = null;
			String doc_name = bo.getString("DOC_NAME");
			if (formFile != null) {
				dc = new DCContext(UserContext.fromUID("admin"),
						DCProfileManager.getDCProfile(formFile.getAppId(), "!iweboffice-"), formFile.getAppId(),
						formFile.getProcessInstId(), formFile.getBoItemName(), formFile.getFileName());
				if (StringUtils.isBlank(doc_name)) {
					doc_name = doc_name.substring(0, doc_name.lastIndexOf(".") + 1) + "doc";
				}

			} else {// 说明用户没点击正文，返回附件
				List<FormFile> attFormFiles = SDK.getBOAPI().getFiles(bo.getId(), "ACCESSORY_ATTFILE");
				if (CollectionUtils.isNotEmpty(attFormFiles)) {
					formFile = attFormFiles.get(0);
					dc = SDK.getBOAPI().getFileDCContext(formFile);
				}
			}
			if (dc != null) {
				logger.info("规章制度回传GRC系统,dcfilename={}", dc.getFileName());
				
				String awsForGrcNasPath = ODAppUtil.getAppParamValue("com.whccb.apps.system.integration", "awsForGrcFilePath");
				String toGrcFilePath = awsForGrcNasPath + bo.getString("FILE_PATH") + doc_name;
				logger.info(this.getDescription()+"toGrcFilePath={}", toGrcFilePath);
				
				File toGrcFile = new File(toGrcFilePath);
				if (!toGrcFile.getParentFile().exists()) {// 检查目录是否存在
					toGrcFile.getParentFile().mkdirs();// 创建目录
				}

				bo.set("DOC_NAME", doc_name);
				SDK.getBOAPI().updateByBindId("BO_WHBK_OD_INSTITUTION", pec.getProcessInstance().getId(), "DOC_NAME", doc_name);

				if ("04".equals(bo.get("REG_LEVEL_DICT"))) {// 体系文件
					bo.set("FILENUM", bo.getString("FILE_NO_ID"));
				}

				// 创建文件
				if (toGrcFile.createNewFile()) {
					// 复制文件内容
					copyFile(SDK.getDCAPI().read(dc), toGrcFilePath);
					// 调用GRC接口，告知GRC系统
					ResponseObject ro = sendGrcRequest(toGrcXmlContext(bo));
					if (ro!=null && ro.isOk()) {
						logger.info(this.getDescription()+"调用GRC接口，告知GRC系统成功！");
						return true;
					}
				}
			}
		}
		return false;
	}

	private void copyFile(InputStream inStream, String newPath) throws Exception {
		int byteread = 0;
		if (inStream != null) {
			FileOutputStream fs = new FileOutputStream(newPath);
			byte[] buffer = new byte[inStream.available()];
			while ((byteread = inStream.read(buffer)) != -1) {
				fs.write(buffer, 0, byteread);
			}
			fs.close();
			inStream.close();
		}
	}

	private ResponseObject sendGrcRequest(String context) {
		String url = "";
		try {
			String ia = InetAddress.getLocalHost().getHostAddress();
			if (ia.equals(SDK.getAppAPI().getProperty(ODConstant.SYSTEM_INTEGRATION_APP_ID, "PRODUCT_MACHINE_IP"))) {
				url = ODAppUtil.getAppParamValue("com.whccb.apps.system.integration", "grcReceiveFileUrl");
			} else {
				url = ODAppUtil.getAppParamValue("com.whccb.apps.system.integration", "grcReceiveFileTestUrl");
			}
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		String sourceAppId = "com.whccb.apps.system.integration";
		String aslp = "aslp://com.whccb.apps.system.integration/wsyhSendRequest";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("url", url);
		params.put("content", context);
		ResponseObject ro = SDK.getAppAPI().callASLP(SDK.getAppAPI().getAppContext(sourceAppId), aslp, params);
		return ro;
	}

	private String toGrcXmlContext(BO bo) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
		Date date = new Date();
		String sn = SDK.getRuleAPI().executeAtScript("@getFormCode(AWS,AWS-GRC-Receive,6)");
		if (StringUtils.isNotEmpty(sn)) {
			sn = sn.substring(3);
		}
		StringBuffer result = new StringBuffer("<?xml version='1.0' encoding='UTF-8'?>");
		if (bo != null) {
			result.append("<service>");
			result.append("<SYS_HEAD>");
			result.append("<commCode>cc001</commCode>");
			result.append("<receiverId>grc</receiverId>");
			result.append("<senderDate>").append(dateFormat.format(date)).append("</senderDate>");
			result.append("<senderTime>").append(timeFormat.format(date)).append("</senderTime>");
			result.append("<senderId>aws</senderId>");
			result.append("<senderSN>").append(sn).append("</senderSN>");
			result.append("<tradeCode>GRC_R_0002</tradeCode>");
			result.append("</SYS_HEAD>");
			result.append("<BODY>");
			result.append("<reg_check_innid>").append(bo.getString("REG_CHECK_INNID")).append("</reg_check_innid>");
			result.append("<file_path>").append(bo.getString("FILE_PATH")).append("</file_path>");
			result.append("<doc_name>").append(bo.getString("DOC_NAME")).append("</doc_name>");
			result.append("<file_no>").append(bo.getString("FILENUM")).append("</file_no>");
			result.append("</BODY>");
			result.append("</service>");
		}
		ConsolePrinter.info("result=" + result.toString());
		return result.toString();
	}
}
